package com.example.joke.custom.shape58

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.graphics.Rect
import android.util.AttributeSet
import android.view.View
import kotlin.math.sqrt

class ShapeView : View {

    private var mPaint: Paint = Paint()
    private var mPath: Path? = null
    private var mCurrentShape = Shape.Circle
    enum class Shape {
        Circle,
        Square,
        Triangle
    }

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        mPaint.isAntiAlias = true
        mPaint.isDither = true
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val width = MeasureSpec.getSize(widthMeasureSpec)
        val height = MeasureSpec.getSize(heightMeasureSpec)
        setMeasuredDimension(if (width > height) height else width, if (width > height) height else width)
    }

    override fun onDraw(canvas: Canvas?) {
        when (mCurrentShape) {
            Shape.Circle -> {
                mPaint.color = Color.YELLOW
                val center = width / 2
                canvas?.drawCircle(center.toFloat(), center.toFloat(), center.toFloat(), mPaint)
            }
            Shape.Square -> {
                mPaint.color = Color.BLUE
                canvas?.drawRect(Rect(0, 0, width, height), mPaint)
            }
            Shape.Triangle -> {
                mPaint.color = Color.RED
                if (mPath == null) {
                    mPath = Path()
                }
                // 等边三角形，角度60，1，2，根3
                mPath!!.moveTo((width / 2).toFloat(), 0F)
                mPath!!.lineTo(0F, (sqrt(3.0) * width / 2).toFloat())
                mPath!!.lineTo(width.toFloat(), (sqrt(3.0) * width / 2).toFloat())
                mPath!!.close()
                canvas?.drawPath(mPath!!, mPaint)
            }
        }
    }

    fun exchangeShape() {
        mCurrentShape = when (mCurrentShape) {
            Shape.Circle -> Shape.Square
            Shape.Square -> Shape.Triangle
            Shape.Triangle -> Shape.Circle
        }
        invalidate()
    }

    fun getCurrentShape(): Shape {
        return mCurrentShape
    }


}